﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Telerik.Web.UI;
using GPSTrackingWebsiteManager.ClassManager;

namespace GPSTrackingWebsiteManager.Manager.Pages
{
    public partial class Users : ClassManager.SessionManagerPage
    {

        private void GetAllUsersByCompany(int companyId)
        {
            try
            {
                UsersGrid.DataSource = GPSTrackingDBV2Custom.Data.DataRepository.UsersProvider.GetByCompanyID(companyId);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        public void showErrorMessage(string msg)
        {
            ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "objWindowsMessageManager.show_Error", "objWindowsMessageManager.show_Error('" + msg + "','Usuarios...');", true);
        }

        private GPSTrackingDBV2.Entities.Users Invoke_Entity(Hashtable Entity)
        {
            GPSTrackingDBV2.Entities.Users UserEntity = new GPSTrackingDBV2.Entities.Users();
            try
            {
                UserEntity.Username = Convert.ToString(Entity[GPSTrackingDBV2.Entities.UsersColumn.Username.ToString()]);
                UserEntity.Password = Convert.ToString(Entity[GPSTrackingDBV2.Entities.UsersColumn.Password.ToString()]);
                UserEntity.Identification = Convert.ToString(Entity[GPSTrackingDBV2.Entities.UsersColumn.Identification.ToString()]);
                UserEntity.Name = Convert.ToString(Entity[GPSTrackingDBV2.Entities.UsersColumn.Name.ToString()]);
                UserEntity.FirstName = Convert.ToString(Entity[GPSTrackingDBV2.Entities.UsersColumn.FirstName.ToString()]);
                UserEntity.LastName = Convert.ToString(Entity[GPSTrackingDBV2.Entities.UsersColumn.LastName.ToString()]);
                UserEntity.Email = Convert.ToString(Entity[GPSTrackingDBV2.Entities.UsersColumn.Email.ToString()]);
                UserEntity.Mobile = Convert.ToString(Entity[GPSTrackingDBV2.Entities.UsersColumn.Mobile.ToString()]);
                UserEntity.Phone = Convert.ToString(Entity[GPSTrackingDBV2.Entities.UsersColumn.Phone.ToString()]);
                UserEntity.IsActive = Convert.ToBoolean(Entity[GPSTrackingDBV2.Entities.UsersColumn.IsActive.ToString()]);
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return UserEntity;

        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                GridSortExpression expression = new GridSortExpression();
                expression.FieldName = GPSTrackingDBV2.Entities.UsersColumn.Username.ToString();
                expression.SetSortOrder("Ascending");
                this.UsersGrid.MasterTableView.SortExpressions.AddSortExpression(expression);
            }
        }

        protected void UsersGrid_NeedDataSource(object sender, Telerik.Web.UI.GridNeedDataSourceEventArgs e)
        {
            try
            {
                GetAllUsersByCompany(getSessionManager().CompanyIDSelectedComboBox);
                UsersGrid.Height = Unit.Parse(HiddenFieldHeight.Value.ToString());
            }
            catch (Exception ex)
            {
                HiddenFieldError.Value = ClassManager.CustomExceptionManager.Generate_Error(ex.Message);            
            }
        }

        protected void UsersGrid_UpdateCommand(object sender, Telerik.Web.UI.GridCommandEventArgs e)
        {
            GPSTrackingDBV2.Data.TransactionManager tm = GPSTrackingDBV2.Data.DataRepository.Provider.CreateTransaction();
            try
            {               
                GridEditableItem item = e.Item as GridEditableItem;
                Hashtable Entity = new Hashtable();
                item.ExtractValues(Entity);

                GPSTrackingDBV2.Entities.Users UserEntity = Invoke_Entity(Entity);
                UserEntity.OriginalUsername = UserEntity.Username;
                UserEntity.CompanyId = getSessionManager().CompanyIDSelectedComboBox;
                UserEntity.OriginalCompanyId = getSessionManager().CompanyIDSelectedComboBox;
                UserEntity.Password = item.SavedOldValues["Password"].ToString();

                GPSTrackingDBV2.Data.DataRepository.UsersProvider.Update(UserEntity);
            }
            catch (Exception ex)
            {
                tm.Rollback();
                HiddenFieldError.Value = ClassManager.CustomExceptionManager.Generate_Error(ex.Message);            
                showErrorMessage("No se puede actualizar el usuario porque esta asociado a un otros registros.");
            }
        }

        protected void UsersGrid_DeleteCommand(object sender, Telerik.Web.UI.GridCommandEventArgs e)
        {
            GPSTrackingDBV2.Data.TransactionManager tm = GPSTrackingDBV2.Data.DataRepository.Provider.CreateTransaction();
            try
            {
                tm.BeginTransaction();
                GridEditableItem item = e.Item as GridEditableItem;
                Hashtable Entity = new Hashtable();
                item.ExtractValues(Entity);

                GPSTrackingDBV2.Entities.Users UserEntity = Invoke_Entity(Entity);

                GPSTrackingDBV2.Data.DataRepository.UsersByUsersGroupsProvider.Delete(tm, UserEntity.Username, int.Parse(Entity["UserGroupId"].ToString()), getSessionManager().CompanyIDSelectedComboBox);

                GPSTrackingDBV2.Data.DataRepository.UsersProvider.Delete(tm, UserEntity.Username, getSessionManager().CompanyIDSelectedComboBox);

                tm.Commit();
            }
            catch (Exception ex)
            {
                tm.Rollback();
                HiddenFieldError.Value = ClassManager.CustomExceptionManager.Generate_Error(ex.Message);            
                if (ex.Message.Contains("UsersByGPSGroups"))
                    showErrorMessage("No se puede eliminar el usuario porque esta asociado a un grupo de dispositivos.");
                else
                {
                    showErrorMessage("No se puede eliminar el usuario porque esta asociado a un otros registros.");
                }
            }
        }

        protected void UsersGrid_ItemDataBound(object sender, GridItemEventArgs e)
        {
            if (e.Item.OwnerTableView.IsItemInserted && e.Item.IsInEditMode) //item is about to be inserted  
            {
                TextBox txtid;
                GridEditableItem insertItem = (GridEditableItem)e.Item;
                txtid = (TextBox)insertItem["Password"].Controls[0];
                txtid.ReadOnly = false;
                txtid.TextMode = TextBoxMode.Password;
                txtid = (TextBox)insertItem["Username"].Controls[0];
                txtid.ReadOnly = false;
            }
            if (!(e.Item.OwnerTableView.IsItemInserted) && e.Item.IsInEditMode)   //item is about to be edit
            {
                TextBox txtid;
                GridEditableItem editItem = (GridEditableItem)e.Item;
                txtid = (TextBox)editItem["Password"].Controls[0];
                txtid.ReadOnly = true;
                txtid.TextMode = TextBoxMode.Password;
                txtid = (TextBox)editItem["Username"].Controls[0];
                txtid.ReadOnly = true;
            }  
        }

        protected void lbClearFilters_Click(object sender, EventArgs e)
        {
            UsersGrid.MasterTableView.FilterExpression = string.Empty;

            foreach (GridColumn column in UsersGrid.MasterTableView.RenderColumns)
            {
                if (column is GridBoundColumn)
                {
                    GridBoundColumn boundColumn = column as GridBoundColumn;
                    boundColumn.CurrentFilterValue = string.Empty;                        
                }
                else { 
                    if(column is GridCheckBoxColumn){
                        GridCheckBoxColumn boundCheckColumn = column as GridCheckBoxColumn;
                        boundCheckColumn.CurrentFilterValue = "true";
                    }
                }
            }
            UsersGrid.MasterTableView.Rebind();
        }

        protected SessionManager getSessionManager() {
            return (SessionManager)HttpContext.Current.Session["SessionManager"];
        }

        protected void lbShowError_Click(object sender, EventArgs e)
        {
            showErrorMessage(HiddenFieldError.Value);
        }
    }
}